package com.samehope.ar.init;

import org.reflections.Reflections;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Description: 应用里的所有mapping的容器
 * @Author: ZhangLuo
 * @Email: 1946430@qq.com
 */
@Component
public class MappingContainer implements ApplicationRunner {

    private List<String> mappingList = new ArrayList<>();

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Reflections reflections = new Reflections("com.samehope.ar.controller");
        Set<Class<?>> controllers = reflections.getTypesAnnotatedWith(RestController.class);
        for (Class<?> controller : controllers) {
            RequestMapping requestMapping = controller.getAnnotation(RequestMapping.class);
            StringBuilder uri = new StringBuilder();
            if (requestMapping != null) {
                uri.append(requestMapping.value()[0]);
            }
            Method[] methods = controller.getMethods();
            for (Method method : methods) {
                RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                if (annotation != null) {
                    mappingList.add(uri.toString() + annotation.value()[0]);
                }
            }
        }
    }

    /**
     * 判断uri是否存在
     * @param uri
     * @return
     */
    public boolean exist(String uri) {
        return mappingList.contains(uri);
    }
}
